package com.houxy.controller;

import com.houxy.repository.model.bo.RegisterBO;
import com.houxy.repository.model.entity.User;
import com.houxy.service.RegisterService;
import com.houxy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LiuYiMing
 * @date 2018/11/1 12:30
 * @describe：
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    public RegisterService registerService;

    @RequestMapping("/login")
    public String login(User user, HttpSession session) {
        User currentUse = userService.userLogin(user);
        if (currentUse != null) {
            session.setAttribute("currentUser", currentUse);
            return "front/index";
        } else {
            session.setAttribute("errInfo", "用户名密码错误！");
            return "front/index";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("currentUser");
        session.removeAttribute("errInfo");
        return "front/index";
    }

    @RequestMapping("/userEdit")
    public String userEdit(User user, HttpSession session) {
        boolean updateUser = userService.updateUser(user);
        if (updateUser == true) {
            session.setAttribute("result", "修改信息成功，重新登录后生效！");
            return "common/msg";
        }
        session.setAttribute("result", "修改信息失败，请重试或联系管理员！");
        return "common/msg";
    }

    @RequestMapping("/registerManager")
    public ModelAndView registerManager(Integer userId) {
        List<RegisterBO> registerByUserList = new ArrayList<>();
        if (userId != null) {
            registerByUserList = registerService.findRegisterByUser(userId);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("registerByUserList", registerByUserList);
        modelAndView.setViewName("auser/register/userRegisterManager");
        return modelAndView;
    }

    @RequestMapping("/addUser")
    public String addUser(User user, HttpSession session) {
        String result = userService.registerUser(user);
        session.setAttribute("addUserInfo", result);
        return "front/userinfo/addUserResult";
    }
}
